package com.jinlejia.erp.ui.house;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.freedom.yefeng.yfrecyclerview.YfListInterface;
import com.freedom.yefeng.yfrecyclerview.YfListMode;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.SearchDistrictAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.BaseActivity;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.EstateBean;
import com.jinlejia.erp.bean.InterestCommunityBean;
import com.jinlejia.erp.common.RecycleViewDivider;
import com.jinlejia.erp.databinding.ActivitySearchDistrictBinding;
import com.jinlejia.erp.ui.common.CommonDeleteDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.litesuits.orm.db.assit.WhereBuilder;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 选择小区
 */
public class SearchDistrictActivity extends BaseActivity {


    SearchDistrictAdapter adapter;
//    HashMap<Integer, Boolean> sMap;
    private ProgressDialog progressDialog;
    private ArrayList<String> selectList = new ArrayList<>();
    ArrayList<InterestCommunityBean> arrayList = new ArrayList<>();

    private ActivitySearchDistrictBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_search_district);
        binding.btBack.setOnClickListener(this::onClick);
        binding.btClear.setOnClickListener(this::onClick);
        binding.btHasCheck.setOnClickListener(this::onClick);
        initView();
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_clear:
                binding.etSearchText.setText("");
                break;
            case R.id.bt_has_check:

                    for( int i = 0 ; i< arrayList.size();i++ ) {
                        InterestCommunityBean icb = arrayList.get(i);
                        DbUtil.getDB(SearchDistrictActivity.this).single().delete(WhereBuilder.create(InterestCommunityBean.class, "estate=?", new String[]{icb.getEstate()}));
                        DbUtil.getDB(SearchDistrictActivity.this).single().save(icb);
                    }

                Intent intent = new Intent(this, HasSelectDistrictActivity.class);
                intent.putExtra("list", arrayList);
                intent.putExtra("csCode", getIntent().getStringExtra("csCode"));
                intent.putExtra("type", getIntent().getStringExtra("type"));
                intent.putExtra("select", selectList);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void initView() {
        progressDialog = new ProgressDialog(this,"请稍等...");
        binding.etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() > 0) {
                    searchData();
                    binding.btClear.setVisibility(View.VISIBLE);
                } else {
                    binding.btClear.setVisibility(View.INVISIBLE);
                }
            }
        });

        binding.yfrvSearchResult.setHasFixedSize(true);
        binding.yfrvSearchResult.setLayoutManager(new LinearLayoutManager(this));
        binding.yfrvSearchResult.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.VERTICAL, 2, getResources().getColor(R.color.colorDivider)));
        ArrayList list = new ArrayList();
        adapter = new SearchDistrictAdapter(list, "", "CHECK");
        binding.yfrvSearchResult.setAdapter(adapter);
        adapter.setOnSelectedListiner(new SearchDistrictAdapter.OnSelectedListiner() {
            @Override
            public void OnSelected(EstateBean icb) {
                if( selectList.contains( icb.getEstateName() ) ){
                    arrayList.remove(icb);
                    selectList.remove(icb.getEstateName());
                }else {
                    selectList.add(icb.getEstateName());
                    InterestCommunityBean interestCommunityBean = new InterestCommunityBean();
                    interestCommunityBean.setEstate(icb.getEstateName());
                    interestCommunityBean.setArea(icb.getArea());
                    interestCommunityBean.setCounty(icb.getCounty());
                    arrayList.add(interestCommunityBean);
                }
                if (selectList.size() > 0) {
                    binding.btHasCheck.setText("已选(" + selectList.size() + ")");
                    binding.bootomLayout.setVisibility(View.VISIBLE);
                } else {
                    binding.bootomLayout.setVisibility(View.GONE);
                }
            }
        });

        ArrayList<InterestCommunityBean> historyList = new ArrayList();
        ArrayList<EstateBean> historyList1 = new ArrayList();
        historyList.addAll(DbUtil.getDB(SearchDistrictActivity.this).single().query(InterestCommunityBean.class));
        Collections.reverse(historyList);
        if (historyList.size() > 20)
            DbUtil.getDB(SearchDistrictActivity.this).single().delete(historyList.subList(19, historyList.size()));
        for (InterestCommunityBean interestCommunityBean:historyList) {
            EstateBean estateBean = new EstateBean();
            estateBean.setEstateName(interestCommunityBean.getEstate());
            estateBean.setArea(interestCommunityBean.getArea());
            estateBean.setCounty(interestCommunityBean.getCounty());
            historyList1.add(estateBean);
        }
        adapter.setData(historyList1);
        if (historyList.size() > 0)
            adapter.addFooter("清空历史");
        adapter.setOnFooterViewClickListener(new YfListInterface.OnFooterViewClickListener() {
            @Override
            public void onFooterViewClick(View view, Object o) {

                CommonDeleteDialog dialog = new CommonDeleteDialog(SearchDistrictActivity.this, "清空历史", "确定清空历史记录?");
                dialog.show();
                dialog.setConfirmListener(new CommonDeleteDialog.OnConfirmListener() {
                    @Override
                    public void confirm() {
                        DbUtil.getDB(SearchDistrictActivity.this).single().delete(InterestCommunityBean.class);
                        adapter.getData().clear();
                        adapter.changeMode(YfListMode.MODE_EMPTY);
                    }
                });

            }
        });

    }

    private void searchData() {
        progressDialog.show();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("reNameLike", binding.etSearchText.getText().toString());
        OkHttpUtils.postString()
                .url(ApiConfig.HOUSE_SOURCE_QUERYE_STATE_LIST)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(SearchDistrictActivity.this, response, adapter)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            JSONArray list = data.getJSONArray("realEstateList");
                            //数据列表
                            ArrayList<EstateBean> beans = (ArrayList<EstateBean>) JSON.parseArray(list.toString(), EstateBean.class);

                            adapter.setWord(binding.etSearchText.getText().toString());
                            adapter.setData(beans);
                            adapter.removeAllFooters();
                        }
                    }
                });

    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
